package com.uduemc.jcms.backend.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.uduemc.jcms.backend.BackendModule;
import com.uduemc.jcms.backend.component.BackendLoginForm;
import com.uduemc.jcms.backend.service.IBJcmsBackendUserService;
import com.uduemc.jcms.common.utils.JsonResult;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;

@Controller
@RequestMapping(BackendModule.BaseRequest)
public class BBackendController {

	@Autowired
	IBJcmsBackendUserService bjcmsBackendUserServiceImpl;

	@Autowired
	BackendLoginForm backendLoginForm;

	// 登录页面
	@GetMapping("/login.html")
	public ModelAndView login(ModelAndView model) {

		model.addObject("loginUsername", "admin");
		model.addObject("loginPassword", "Ab123456");
		model.setViewName(BackendModule.ModuleName + "/login");
		return model;
	}

	// 登出页面
	@GetMapping("/logout.html")
	public void logout(HttpServletResponse response) throws IOException {
		backendLoginForm.logout();
		response.sendRedirect(BackendModule.LoginUri);
		return;
	}

	// 验证码图片
	@GetMapping("/captcha-image.jpg")
	public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
		LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(96, 32, 4, 20);
		String code = lineCaptcha.getCode();
		request.getSession().setAttribute("captcha", code);
		lineCaptcha.write(response.getOutputStream());
	}

	// 登录页面
	@PostMapping("/login-submit.html")
	@ResponseBody
	public JsonResult loginSubmit(@RequestParam("captcha") String captcha, @RequestParam("username") String username,
			@RequestParam("password") String password) {
		return bjcmsBackendUserServiceImpl.loginSubmit(captcha, username, password);
	}
}
